package com.sxhnpg.web.action;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.sxhnpg.constant.Constants;
import com.sxhnpg.exception.SxhnpgException;
import com.sxhnpg.manager.TableManager;
import com.sxhnpg.manager.TravelManager;
import com.sxhnpg.manager.UserDetailManager;
import com.sxhnpg.manager.UserManager;
import com.sxhnpg.model.AgencyExcel;
import com.sxhnpg.model.Table;
import com.sxhnpg.model.TravelAgencyInfo;
import com.sxhnpg.model.User;
import com.sxhnpg.model.UserDetail;
import com.sxhnpg.util.DigestUtil;
import com.sxhnpg.util.ExportExcel;



public class TravelLoginAction extends BaseAction{

	private String agencyId;
	private String travelAgencyName;
	private String carNumber;
	private String carType;
	private int countPeople;
	private String city;
	private String viewpoint;
	private int isDriver;
	private String driver;
	private String guide;
	private int isContract;
	private Date registerDate;
	private String remainTime;
	private String subsidyPrice;
	private String travelerPrice;
	private String operatePeople;
	private String lastPlace;
	private String mobile;
	private String payType;
	private String totalPrice;
	private int handle;
	
	private String isDedicated;
	
	private String monthTableName;
	// 旅行社管理器
	private TravelManager travelManager;
	
	public void setTravelManager(TravelManager travelManager) {
		this.travelManager = travelManager;
	}
	
	private TableManager tableManager;
	
	public void setTableManager(TableManager tableManager) {
		this.tableManager = tableManager;
	}
	
	private static Logger logger = Logger.getLogger(TravelLoginAction.class);  
	
	// 获得当前月表名
	public String getCurrentMonthTableName(){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM");
		Calendar cl = Calendar.getInstance();
		String currentMonthTableName = "sxhnpg_agency_" + sdf.format(cl.getTime());
		return currentMonthTableName;
	}
	// 旅行社基本信息列表
	public String travelList() throws SxhnpgException{
		Map<String, Object> session=(Map<String, Object>)ActionContext.getContext().getSession();
		try{
			User userInSession = (User)session.get(Constants.LOGIN_USER_INFO);
			// 过滤
			if(userInSession == null){
				goLoginPage();
				return null;
			}
			
			String currentMonthTableName = null;
			if(monthTableName == null || "".equals(monthTableName)){
				currentMonthTableName = getCurrentMonthTableName();
			}else{
				currentMonthTableName = monthTableName;
			}
			// 当前月登记信息
			List<TravelAgencyInfo> travelList = new ArrayList<TravelAgencyInfo>(); 
			travelList = travelManager.findTravelListByMonthTableName(currentMonthTableName);
			ServletActionContext.getRequest().setAttribute("travelList", travelList);
			
			// 获得月表集合
			List<Table> tableList = new ArrayList<Table>();
			tableList = tableManager.findTables();
			ServletActionContext.getRequest().setAttribute("tableList", tableList);
			
			ServletActionContext.getRequest().setAttribute("currentMonthTableName", currentMonthTableName);

		}catch(Exception e) {
			logger.error("查看旅行社基本信息列表出错：",e);
			throw new SxhnpgException();
		}
		return "list";
	}
	
	// 导出登记列表
	public String exportExcel() throws SxhnpgException{
		Map<String, Object> session=(Map<String, Object>)ActionContext.getContext().getSession();
		HttpServletResponse response = ServletActionContext.getResponse();
		try{
			User userInSession = (User)session.get(Constants.LOGIN_USER_INFO);
			// 过滤
			if(userInSession == null){
				goLoginPage();
				return null;
			}
			
			String currentMonthTableName = null;
			if(monthTableName == null || "".equals(monthTableName)){
				currentMonthTableName = getCurrentMonthTableName();
			}else{
				currentMonthTableName = monthTableName;
			}
			// 当前月登记信息
			List<TravelAgencyInfo> travelList = new ArrayList<TravelAgencyInfo>(); 
			travelList = travelManager.findTravelListByMonthTableName(currentMonthTableName);
			// 组装数据   
	        ExportExcel<AgencyExcel> ex = new ExportExcel<AgencyExcel>();  
	        String[] headers =  
	        	{ "登记时间", "旅行社","车牌号", "车型",  "城市","景点" ,"是否司机","司机","导游","联系方式","是否签约","停留时间","司导补贴","人数","人头费","合计","付款方式"};  
	        List<AgencyExcel> dataset = new ArrayList<AgencyExcel>();  
	        for(TravelAgencyInfo travelAgencyInfo : travelList){
	        	String isDriver2 = "";	// 是否司机
	        	String isContract2 = "";	// 是否签约
	        	String payType2 = "";	// 付款方式
	        	String carType2 = "";	//车型
//	        	String isDedicated2 = "";	// 是否专线
//	        	String remainTime2 = "";	//停留时间
	        	if(travelAgencyInfo.getIsDriver() == 1){
	        		isDriver2 = "是";
	        	}else{
	        		isDriver2 = "否";
	        	}
	        	if(Integer.parseInt(travelAgencyInfo.getCarType()) == 0){
	        		carType2 = "中巴";
	        	}else{
	        		carType2 = "大巴";
	        	}
	        	if(travelAgencyInfo.getIsContract() == 1){
	        		isContract2 = "是";
	        	}else{
	        		isContract2 = "否";
	        	}
	        	if("0".equals(travelAgencyInfo.getPayType())){
	        		payType2 = "留存";
	        	}else{
	        		payType2 = "现结";
	        	}
	        	
//	        	if("0".equals(travelAgencyInfo.getRemainTime())){
//	        		remainTime2 = "1.5小时以下";
//	        	}else if("1".equals(travelAgencyInfo.getRemainTime())){
//	        		remainTime2 = "1.5小时~2.5小时";
//	        	}else if("2".equals(travelAgencyInfo.getRemainTime())){
//	        		remainTime2 = "2.5小时~3.5小时";
//	        	}else if("3".equals(travelAgencyInfo.getRemainTime())){
//	        		remainTime2 = "3.5小时~4.5小时";
//	        	}else if("4".equals(travelAgencyInfo.getRemainTime())){
//	        		remainTime2 = "4.5小时以上";
//	        	}
	        	
//	        	if(travelAgencyInfo.getIsDedicated() == 1){
//	        		isDedicated2 = "是";
//	        	}else{
//	        		isDedicated2 = "否";
//	        	}
		        dataset.add(new AgencyExcel(travelAgencyInfo.getRegisterDate(),
		        		travelAgencyInfo.getTravelAgencyName(),
		        		travelAgencyInfo.getCarNumber(),
		        		carType2,
		        		travelAgencyInfo.getCity(),
		        		travelAgencyInfo.getViewpoint(),
		        		isDriver2,
		        		travelAgencyInfo.getDriver(),
		        		travelAgencyInfo.getGuide(),
		        		travelAgencyInfo.getIsDedicated(),
		        		isContract2,
		        		travelAgencyInfo.getRemainTime(),
		        		travelAgencyInfo.getSubsidyPrice(),
		        		String.valueOf(travelAgencyInfo.getCountPeople()),
		        		travelAgencyInfo.getTravelerPrice(),
		        		travelAgencyInfo.getTotalPrice(),
		        		payType2));  
	        }
	        String fileName = "旅行社登记月表_" + currentMonthTableName.substring(14) +".xls";
	        response.setContentType("application/vnd.ms-excel");//设置生成的文件类型
	        response.setHeader("Content-Disposition", "filename="+ new String(fileName.getBytes("gb2312"), "iso8859-1"));//设置文件头编码方式和文件名

	        OutputStream out = response.getOutputStream();;
			try {
				ex.exportExcel(headers, dataset, out);
				out.close();
				out.flush();
			} catch (FileNotFoundException e) {
				logger.error("找不到导出文件：" + e);
			} catch (IOException e) {
				logger.error("流错误：" + e);
			}
			
			// 获得月表集合
//			List<Table> tableList = new ArrayList<Table>();
//			tableList = tableManager.findTables();
//			ServletActionContext.getRequest().setAttribute("tableList", tableList);
//			
//			ServletActionContext.getRequest().setAttribute("currentMonthTableName", currentMonthTableName);

		}catch(Exception e) {
			logger.error("导出出错：",e);
			throw new SxhnpgException();
		}
		return null;
	}
	
	// 添加旅行社信息
	public String addTravelAgencyInfo() throws SxhnpgException{
		Map<String, Object> session=(Map<String, Object>)ActionContext.getContext().getSession();
		try{
			User userInSession = (User)session.get(Constants.LOGIN_USER_INFO);
			// 过滤
			if(userInSession == null){
				goLoginPage();
				return null;
			}
			
			String currentMonthTableName = null;
			if(monthTableName == null || "".equals(monthTableName)){
				currentMonthTableName = getCurrentMonthTableName();
			}else{
				currentMonthTableName = monthTableName;
			}
			
			TravelAgencyInfo travelAgencyInfo = new TravelAgencyInfo();
			travelAgencyInfo.setTravelAgencyName(travelAgencyName);
			travelAgencyInfo.setCarNumber(carNumber);
			travelAgencyInfo.setCarType(carType);
			travelAgencyInfo.setPayType(payType);
			travelAgencyInfo.setCity(city);
			travelAgencyInfo.setViewpoint(viewpoint);
			travelAgencyInfo.setIsDriver(isDriver);
			travelAgencyInfo.setDriver(driver);
			travelAgencyInfo.setGuide(guide);
			travelAgencyInfo.setIsContract(isContract);
			travelAgencyInfo.setRemainTime(remainTime);
			travelAgencyInfo.setCountPeople(countPeople);
			travelAgencyInfo.setSubsidyPrice(subsidyPrice);
			travelAgencyInfo.setIsDedicated(isDedicated);
			
			travelAgencyInfo.setTravelerPrice(travelerPrice);
			travelAgencyInfo.setTotalPrice(String.valueOf(Integer.parseInt(subsidyPrice) + Integer.parseInt(travelerPrice)*countPeople));
			
			// 计算单个旅客价钱
//			int travelerPriceInt  = 0;
//			if("0".equals(remainTime)){
//				travelerPriceInt = 0;
//			}else if("1".equals(remainTime)){
//				travelerPriceInt = 18;
//			}else if("2".equals(remainTime)){
//				travelerPriceInt = 25;
//			}else if("3".equals(remainTime)){
//				travelerPriceInt = 35;
//			}else if("4".equals(remainTime)){
//				travelerPriceInt = 60;
//			}
			// 是否专线，1代表专线，0，不是专线，专线每个旅客加20元
//			int dedicatedPrice  = 0;
//			if(isDedicated == 0){
//				dedicatedPrice = 0;
//			}else if(isDedicated == 1){
//				dedicatedPrice = 20;
//			}
//			int travelerTotalPrice = travelerPriceInt + dedicatedPrice;
//			travelAgencyInfo.setTravelerPrice(String.valueOf(travelerTotalPrice));
			
			// 总价钱 = 单个旅客价钱 * 人数 + 司导补贴
//			int totalPrice2 = travelerTotalPrice * countPeople + Integer.parseInt(subsidyPrice);
			
//			travelAgencyInfo.setTotalPrice(String.valueOf(totalPrice2));
			
			travelAgencyInfo.setRegisterDate(new Date());
			travelAgencyInfo.setOperatePeople(userInSession.getUserid());
			travelAgencyInfo.setHandle(0);
			
			travelManager.insertTravel(currentMonthTableName,travelAgencyInfo);
			
			ServletActionContext.getRequest().setAttribute(Constants.OPT_SUCCESS_INFO, "登记信息成功！");
		}catch(Exception e) {
			logger.error("登记信息出错：",e);
			throw new SxhnpgException();
		}
		return "result";
	}
	
	// 删除信息
	public String removeTravel() throws SxhnpgException{
		Map<String, Object> session=(Map<String, Object>)ActionContext.getContext().getSession();
		try{
			User userInSession = (User)session.get(Constants.LOGIN_USER_INFO);
			// 过滤
			if(userInSession == null){
				goLoginPage();
				return null;
			}
			String currentMonthTableName = null;
			if(monthTableName == null || "".equals(monthTableName)){
				currentMonthTableName = getCurrentMonthTableName();
			}else{
				currentMonthTableName = monthTableName;
			}
			travelManager.removeTravel(currentMonthTableName,Integer.parseInt(agencyId));
			ServletActionContext.getRequest().setAttribute(Constants.OPT_SUCCESS_INFO, "删除信息成功！");
		}catch(Exception e) {
			logger.error("删除信息出错：",e);
			throw new SxhnpgException();
		}
		return "result";
	}
	
	// 跳转修改页面
	public String goModifyTravelPage() throws SxhnpgException{
		Map<String, Object> session=(Map<String, Object>)ActionContext.getContext().getSession();
		try{
			User userInSession = (User)session.get(Constants.LOGIN_USER_INFO);
			// 过滤
			if(userInSession == null){
				goLoginPage();
				return null;
			}
			String currentMonthTableName = null;
			if(monthTableName == null || "".equals(monthTableName)){
				currentMonthTableName = getCurrentMonthTableName();
			}else{
				currentMonthTableName = monthTableName;
			}
			TravelAgencyInfo travelAgencyInfo = travelManager.findTravel(currentMonthTableName,Integer.parseInt(agencyId));
			
			// 用于进度条判断
//			int progressCount = 0;
//			if(!"".equals(user.getUserDetail().getEmail()) && user.getUserDetail().getEmail() != null){
//				progressCount += 10;
//			}
//			if(!"".equals(user.getUserDetail().getMobile()) && user.getUserDetail().getMobile() != null){
//				progressCount += 10;
//			}
			
//			ServletActionContext.getRequest().setAttribute("progressCount", progressCount);
			ServletActionContext.getRequest().setAttribute("currentMonthTableName", currentMonthTableName);
			ServletActionContext.getRequest().setAttribute("travelAgencyInfo", travelAgencyInfo);
			
		}catch(Exception e) {
			logger.error("跳转修改页面失败：",e);
			throw new SxhnpgException();
		}
		return "modifyPage";
	}
	
	// 修改登记信息
	public String modifyTravel() throws SxhnpgException{
		Map<String, Object> session=(Map<String, Object>)ActionContext.getContext().getSession();
		try{
			User userInSession = (User)session.get(Constants.LOGIN_USER_INFO);
			// 过滤
			if(userInSession == null){
				goLoginPage();
				return null;
			}
			String currentMonthTableName = null;
			if(monthTableName == null || "".equals(monthTableName)){
				currentMonthTableName = getCurrentMonthTableName();
			}else{
				currentMonthTableName = monthTableName;
			}
			TravelAgencyInfo travelAgencyInfo = new TravelAgencyInfo();
			
			travelAgencyInfo.setAgencyId(agencyId);
			travelAgencyInfo.setTravelAgencyName(travelAgencyName);
			travelAgencyInfo.setCarNumber(carNumber);
			travelAgencyInfo.setCarType(carType);
			travelAgencyInfo.setPayType(payType);
			travelAgencyInfo.setCity(city);
			travelAgencyInfo.setViewpoint(viewpoint);
			travelAgencyInfo.setIsDriver(isDriver);
			travelAgencyInfo.setDriver(driver);
			travelAgencyInfo.setGuide(guide);
			travelAgencyInfo.setIsContract(isContract);
			travelAgencyInfo.setRemainTime(remainTime);
			travelAgencyInfo.setCountPeople(countPeople);
			travelAgencyInfo.setSubsidyPrice(subsidyPrice);
			travelAgencyInfo.setIsDedicated(isDedicated);
			
			travelAgencyInfo.setTravelerPrice(travelerPrice);
			travelAgencyInfo.setTotalPrice(String.valueOf(Integer.parseInt(subsidyPrice) + Integer.parseInt(travelerPrice)*countPeople));
			
			
			// 计算单个旅客价钱
//			int travelerPriceInt  = 0;
//			if("0".equals(remainTime)){
//				travelerPriceInt = 0;
//			}else if("1".equals(remainTime)){
//				travelerPriceInt = 18;
//			}else if("2".equals(remainTime)){
//				travelerPriceInt = 25;
//			}else if("3".equals(remainTime)){
//				travelerPriceInt = 35;
//			}else if("4".equals(remainTime)){
//				travelerPriceInt = 60;
//			}
			// 是否专线，1代表专线，0，不是专线，专线每个旅客加20元
//			int dedicatedPrice  = 0;
//			if(isDedicated == 0){
//				dedicatedPrice = 0;
//			}else if(isDedicated == 1){
//				dedicatedPrice = 20;
//			}
//			int travelerTotalPrice = travelerPriceInt + dedicatedPrice;
//			travelAgencyInfo.setTravelerPrice(String.valueOf(travelerTotalPrice));
			
			// 总价钱 = 单个旅客价钱 * 人数 + 司导补贴
//			int totalPrice2 = travelerTotalPrice * countPeople + Integer.parseInt(subsidyPrice);
//			travelAgencyInfo.setTotalPrice(String.valueOf(totalPrice2));
			

			travelAgencyInfo.setOperatePeople(userInSession.getUserid());

			travelManager.updateTravel(currentMonthTableName,travelAgencyInfo);
				
			ServletActionContext.getRequest().setAttribute(Constants.OPT_SUCCESS_INFO, "修改登记成功！");
		}catch(Exception e) {
			logger.error("修改登记出错：",e);
			throw new SxhnpgException();
		}
		return "result";
	}
	
	// 处理信息
	public String modifyHandle() throws SxhnpgException{
		Map<String, Object> session=(Map<String, Object>)ActionContext.getContext().getSession();
		try{
			User userInSession = (User)session.get(Constants.LOGIN_USER_INFO);
			// 过滤
			if(userInSession == null){
				goLoginPage();
				return null;
			}
			if(userInSession.getPermission() != 1 && userInSession.getPermission() != 2){
				return null;
			}
			String currentMonthTableName = null;
			if(monthTableName == null || "".equals(monthTableName)){
				currentMonthTableName = getCurrentMonthTableName();
			}else{
				currentMonthTableName = monthTableName;
			}

			travelManager.updateHandle(currentMonthTableName,Integer.parseInt(agencyId));
				
			ServletActionContext.getRequest().setAttribute(Constants.OPT_SUCCESS_INFO, "处理信息成功！");
		}catch(Exception e) {
			logger.error("处理信息出错：",e);
			throw new SxhnpgException();
		}
		return "result";
	}
	
	
	
	public String getAgencyId() {
		return agencyId;
	}
	public void setAgencyId(String agencyId) {
		this.agencyId = agencyId;
	}
	public String getTravelAgencyName() {
		return travelAgencyName;
	}
	public void setTravelAgencyName(String travelAgencyName) {
		this.travelAgencyName = travelAgencyName;
	}
	public String getCarNumber() {
		return carNumber;
	}
	public void setCarNumber(String carNumber) {
		this.carNumber = carNumber;
	}
	public String getCarType() {
		return carType;
	}
	public void setCarType(String carType) {
		this.carType = carType;
	}
	public int getCountPeople() {
		return countPeople;
	}
	public void setCountPeople(int countPeople) {
		this.countPeople = countPeople;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getViewpoint() {
		return viewpoint;
	}
	public void setViewpoint(String viewpoint) {
		this.viewpoint = viewpoint;
	}
	public int getIsDriver() {
		return isDriver;
	}
	public void setIsDriver(int isDriver) {
		this.isDriver = isDriver;
	}
	public String getDriver() {
		return driver;
	}
	public void setDriver(String driver) {
		this.driver = driver;
	}
	public String getGuide() {
		return guide;
	}
	public void setGuide(String guide) {
		this.guide = guide;
	}
	public int getIsContract() {
		return isContract;
	}
	public void setIsContract(int isContract) {
		this.isContract = isContract;
	}
	public Date getRegisterDate() {
		return registerDate;
	}
	public void setRegisterDate(Date registerDate) {
		this.registerDate = registerDate;
	}
	public String getRemainTime() {
		return remainTime;
	}
	public void setRemainTime(String remainTime) {
		this.remainTime = remainTime;
	}
	public String getSubsidyPrice() {
		return subsidyPrice;
	}
	public void setSubsidyPrice(String subsidyPrice) {
		this.subsidyPrice = subsidyPrice;
	}
	public String getTravelerPrice() {
		return travelerPrice;
	}
	public void setTravelerPrice(String travelerPrice) {
		this.travelerPrice = travelerPrice;
	}
	public String getOperatePeople() {
		return operatePeople;
	}
	public void setOperatePeople(String operatePeople) {
		this.operatePeople = operatePeople;
	}
	public String getLastPlace() {
		return lastPlace;
	}
	public void setLastPlace(String lastPlace) {
		this.lastPlace = lastPlace;
	}
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
	public String getPayType() {
		return payType;
	}
	public void setPayType(String payType) {
		this.payType = payType;
	}
	public String getTotalPrice() {
		return totalPrice;
	}
	public void setTotalPrice(String totalPrice) {
		this.totalPrice = totalPrice;
	}

	public int getHandle() {
		return handle;
	}
	public void setHandle(int handle) {
		this.handle = handle;
	}
	public String getMonthTableName() {
		return monthTableName;
	}
	public void setMonthTableName(String monthTableName) {
		this.monthTableName = monthTableName;
	}
	public String getIsDedicated() {
		return isDedicated;
	}
	public void setIsDedicated(String isDedicated) {
		this.isDedicated = isDedicated;
	}
	
	
}
